<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="register"
    :title="displayModuleTitle"
    @ok="onOkButtonClick"
    :showFooter="true"
    width="90%"
  >
    <div style="display: flex; flex-direction: row">
      <a-descriptions
        bordered
        :column="2"
        style="flex: 1"
        size="middle"
        width="600px"
        :labelStyle="{ width: '140px' }"
      >
        <a-descriptions-item label="任务项名称" :span="2">{{
          taskExecuteInfo.item?.itemname
        }}</a-descriptions-item>
        <a-descriptions-item label="单元" :span="2">{{
          taskExecuteInfo.unitname
        }}</a-descriptions-item>
        <a-descriptions-item label="执行起止时间" :span="1"
          >{{ moment(taskExecuteInfo.begintm).format('YYYY-MM-DD') }}~{{
            moment(taskExecuteInfo.endtm).format('YYYY-MM-DD')
          }}</a-descriptions-item
        >
        <a-descriptions-item label="执行时间" :span="1">{{
          taskExecuteInfo.executetmstr
        }}</a-descriptions-item>

        <a-descriptions-item label="执行人员" :span="2">{{
          taskExecuteInfo.executor
        }}</a-descriptions-item>
        <a-descriptions-item label="是否执行完成" :span="1"
          ><a-tag :color="taskExecuteInfo.hasexec ? 'green' : 'red'">{{
            taskExecuteInfo.hasexec ? '是' : '否'
          }}</a-tag></a-descriptions-item
        >
        <a-descriptions-item label="是否执行正常" :span="1"
          ><a-tag :color="taskExecuteInfo.isnormal ? 'green' : 'red'">{{
            taskExecuteInfo.isnormal ? '是' : '否'
          }}</a-tag></a-descriptions-item
        >
        <a-descriptions-item label="执行内容描述" :span="2">{{
          taskExecuteInfo.execdescription ?? '-'
        }}</a-descriptions-item>
        <a-descriptions-item label="执行附件" :span="2">
          <a-list
            class="Alist"
            item-layout="horizontal"
            v-if="taskExecuteInfo?.execattachment?.length > 0"
            :data-source="taskExecuteInfo?.execattachment"
          >
            <template #renderItem="{ item }">
              <a-list-item>
                <template #actions>
                  <a @click="downloadFile(item)">下载</a>
                </template>
                <a-list-item-meta>
                  <template #title>
                    <span>{{ item.title }}</span>
                  </template>
                </a-list-item-meta>
              </a-list-item>
            </template>
          </a-list>
          <span v-else>-</span>
        </a-descriptions-item>
        <!-- <a-descriptions-item label="检查表" :span="2">
          <a-button v-if="taskExecuteInfo.checkrecordid" @click="openViewCheckFormValue" type="text"
            >查看检查表</a-button
          >
          <span v-else>-</span>
        </a-descriptions-item> -->
        <a-descriptions-item label="签名" :span="2">
          <a-image
            :src="getImageFileUrlPrefix + taskExecuteInfo.execsign"
            :width="150"
            v-if="taskExecuteInfo.execsign"
          />
          <span v-else>-</span>
        </a-descriptions-item>
      </a-descriptions>
      <div v-if="taskExecuteInfo.checkrecordid" style="margin-left: 10px; flex: 1; width: 600px">
        <h2 style="font-weight: 600; font-size: 14px">{{ checkFormData?.content?.title }}</h2>
        <div style="height: 420px; overflow-y: auto">
          <BasicTable
            @register="registerCheckFormTable"
            :can-resize="true"
            :bordered="true"
            :striped="true"
            :data-source="checkFormData?.dataSource"
          >
            <template #images="{ record }">
              <a-list
                class="Alist"
                item-layout="horizontal"
                v-if="record.images?.length > 0"
                :data-source="record.images"
              >
                <template #renderItem="{ item }">
                  <a-list-item>
                    <template #actions>
                      <a @click="downloadFile(item)">下载</a>
                    </template>
                    <a-list-item-meta>
                      <template #title>
                        <span>{{ item.title }}</span>
                      </template>
                    </a-list-item-meta>
                  </a-list-item>
                </template>
              </a-list>
            </template>
            <!-- <template #toolbar>
              <a-button @click="exportInUserToExcel"> 导出Excel </a-button>
            </template> -->
          </BasicTable>
        </div>
      </div>
      <ViewCheckFormInfo @register="registerViewCheckFormModal" />
    </div>
    <a-divider>确认执行记录信息</a-divider>
    <BasicForm @register="registerForm">
      <template #sign="{ model, field }">
        <div style="margin-bottom: 5px"
          ><a-button type="primary" @click="onOpenEsignModalButtonClick">打开签名板</a-button>
          <a-button danger type="text" v-if="model[field]" @click="setSignValue(null)"
            >清空</a-button
          ></div
        >
        <a-image :src="getImageFileUrlPrefix + model[field]" :width="150" v-if="model[field]" />
      </template>
    </BasicForm>
    <EsignModal @register="registerSignModal" @success="setSignValue" />
  </BasicDrawer>
</template>
<script lang="ts">
  import { computed, defineComponent, onMounted, ref, unref } from 'vue';
  // import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { BasicDrawer, useDrawerInner, useDrawer } from '/@/components/Drawer';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { displayTitle } from '/@/utils/QcUnifyUtil';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { useGlobSetting } from '/@/hooks/setting';
  import EsignModal from '../Component/EsignModal.vue';
  import { useModal } from '/@/components/Modal';
  import { confirmExecuteRecordSchema } from './taskConsole.data';
  import { confirmExecuteRecord } from '/@/api/ehs/taskExecute';
  import { getOneExecuteRecord } from '/@/api/ehs/taskExecute';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { downloadByUrl } from '/@/utils/file/download';
  import { getImageFileApi, getFileApi } from '/@/api/platform/file';
  import { getCheckRecord } from '/@/api/ehs/checkForm';
  import { BasicTable, useTable } from '/@/components/Table';
  const { globalProjectCode } = useGlobSetting();
  import { checkFormColumns } from '../taskBench/taskBench.data';
  const { createMessage } = useMessage();
  import moment from 'moment';
  import { useUserStore } from '/@/store/modules/user';
  export default defineComponent({
    components: { BasicDrawer, BasicForm, EsignModal, BasicTable },
    name: 'ConfirmExecuteDrawer',
    emits: ['success'],
    setup(props, { emit }) {
      const { uploadUrl } = useGlobSetting();
      const userStore = useUserStore();
      const getImageFileUrlPrefix = ref<string>(uploadUrl + getImageFileApi);
      const taskExecuteInfo = ref({});
      const checkFormData = ref();
      const [registerSignModal, { openModal: openEsignModal }] = useModal();
      const [registerForm, { setFieldsValue, resetFields, validate, updateSchema }] = useForm({
        labelWidth: 100,
        schemas: confirmExecuteRecordSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });
      /**
       * 检查表table
       */
      const [registerCheckFormTable] = useTable({
        title: checkFormData.value?.content?.title,
        columns: checkFormColumns, //表头数据
        showTableSetting: false, //是否显示表格设置
        bordered: true,
        ellipsis: false,
        striped: false, //斑马纹
        showIndexColumn: false,
        pagination: false,
        size: 'small',
        scroll: { y: 450 },
      });
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();
      const dataId = ref();
      const [register, { closeDrawer }] = useDrawerInner((data) => {
        resetFields();
        if (data != undefined && data != null) {
          let unrefData = unref(data);
          qcUnifyProps.value = unrefData;
          //接收父组件传递的数据
          if (unrefData?.dataId) {
            dataId.value = unrefData.dataId;
            getOneExecuteRecord(dataId.value).then((res) => {
              taskExecuteInfo.value = {
                ...res,
                execattachment: res.execattachment ? returnAttachment(res.execattachment) : [],
              };
              if (res.checkrecordid && res.checkcontent) {
                let content = res.checkcontent ? JSON.parse(res.checkcontent) : {};
                let dataSource = [];
                dataSource = content.schema
                  .filter((item) => item.component != 'Divider')
                  .map((item) => {
                    return {
                      ...item,
                      result: content.content[item.field]?.value,
                      description: content.content[item.field]?.description,
                      images: returnImages(content.content[item.field]?.images),
                    };
                  });
                checkFormData.value = {
                  ...res,
                  content: content,
                  dataSource: mergeSameValueRow(dataSource, 'parentGroupName'),
                };
                console.log('checkFormData', checkFormData.value);
              }
            });
            setFieldsValue({
              confirmsign: userStore.getUserInfo?.sign,
            });
          }
        }
      });

      /**
       * 合并数组data中指定field的值相同的行时, 需要计算rowSpan来实现
       */
      const mergeSameValueRow = (data, field) => {
        let count = 0; //重复项的第一项
        let indexCount = 1; //下一项
        while (indexCount < data.length) {
          var item = data.slice(count, count + 1)[0]; //获取没有比较的第一个对象
          if (!item[`rowSpan`]) {
            item[`rowSpan`] = 1; //初始化为1
          }
          if (item[field] === data[indexCount][field]) {
            //第一个对象与后面的对象相比，有相同项就累加，并且后面相同项设置为0
            item[`rowSpan`]++;
            data[indexCount][`rowSpan`] = 0;
          } else {
            count = indexCount;
          }
          indexCount++;
        }
        return data;
      };

      /**
       * 下载附件
       */
      function downloadFile(item) {
        downloadByUrl({ url: item.url, fileName: item.name });
      }

      /**
       * 返回JSON格式的附件信息数组
       */
      function returnAttachment(attachment) {
        return JSON.parse(attachment).map((item) => {
          let url = uploadUrl + getFileApi + item.id;
          let title = item.name + '.' + item.type;
          return {
            ...item,
            title,
            url,
          };
        });
      }

      /**
       * 返回JSON格式的图片信息数组
       */
      function returnImages(images) {
        return images.map((item) => {
          let url = uploadUrl + getFileApi + item.id;
          let title = item.name + '.' + item.type;
          return {
            ...item,
            title,
            url,
          };
        });
      }

      function onOpenEsignModalButtonClick() {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '确认执行记录',
          operateString: '签字',
          dataId: dataId.value,
        };
        openEsignModal(true, propsData);
      }

      function setSignValue(sign) {
        setFieldsValue({
          confirmsign: sign,
        });
      }

      async function onOkButtonClick() {
        const values = await validate();
        values.execid = dataId.value;
        values.confirmattachment = JSON.stringify(values.confirmattachment);
        confirmExecuteRecord(values).then((res) => {
          if (!res) {
            createMessage.success('确认执行成功');
            closeDrawer();
            emit('success');
          }
        });
      }

      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });

      onMounted(() => {});

      return {
        register,
        getImageFileUrlPrefix,
        registerSignModal,
        registerForm,
        closeDrawer,
        displayModuleTitle,
        onOkButtonClick,
        setSignValue,
        onOpenEsignModalButtonClick,
        moment,
        downloadFile,
        taskExecuteInfo,
        checkFormData,
        registerCheckFormTable,
      };
    },
  });
</script>
<style scoped>
  :deep(.ant-drawer-content) {
    overflow: hidden;
  }
</style>
